package net.kong.yumo.assa.controller;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import net.kong.yumo.assa.Mapper.orcle.TestMapper;
import net.kong.yumo.assa.Mapper.sqlite.imgMapper;
import net.kong.yumo.assa.pojo.Result;
import net.kong.yumo.assa.pojo.SqliteSequence;
import net.kong.yumo.utils.FileTypeUtils;
  


@RestController()
@RequestMapping("/img") 
public class UploadController {
    private static final Logger log = LoggerFactory.getLogger(UploadController.class);

	@Value("${file.upload.path}")
	private String path = "upload/";
    
	@Autowired
	private SimpleDateFormat ft ;

    @Autowired
    private TestMapper tMapper;

    @Autowired
    private imgMapper iMapper;
    
    @GetMapping("/upload/{in}/1")
    public Result upload(@PathVariable String in) {
    	Result re = new Result();
    	re.setMsg("/upload/{in}/1");
    	  return re;
    }    
    
    @GetMapping("/uploadv1")
    public Result upload1() {
    	Result re = new Result();
    	re.setData(tMapper.selTableMapPram("testtable"));
        return re;
    }
    
    @PostMapping("/multiUploadImg")
    @ResponseBody
    public Result multiUploadImg(HttpServletRequest request) {
    	Result re = new Result();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        boolean fileTypeEnableImg= false ;
        List<String> reData=new ArrayList();
        String paths="";
        File dest = null;
        MultipartFile file = null;
		Date dNow = new Date(); 
		String currentDay = ft.format(dNow);
        for (int i = 0; i < files.size(); i++) {
            file = files.get(i);
            if (file.isEmpty()) {
            	reData.add("上传第" + (++i) + "个文件失败") ;
            	continue ;
            }            
            try {
            	fileTypeEnableImg=FileTypeUtils.multipartFileIsImg(file);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				log.info("filetype get faile:"+e1.getMessage());
				reData.add("上传第" + (++i) + "个文件失败,"+"filetype get faile:"+e1.getMessage()) ;
            	continue ;
			}
            if(!fileTypeEnableImg) {
            	reData.add("上传第" + (++i) + "个文件失败,fileTypeIsNotImg") ;
            	continue ;
            }             
            paths = new File(path).getAbsolutePath()+ "/" +currentDay+ "/" +file.getOriginalFilename();
            dest = new File(paths);
            try {
                file.transferTo(dest);
//                iMapper.addTable("", "", "");
                
                log.info("第" + (i + 1) + "个文件上传成功");                
            	reData.add("第" + (i + 1) + "个文件上传成功.path:"+paths) ;
            } catch (Exception e) {
                log.info("上传第" + (1+i) + "个文件失败,fileSaveFaile-"+e.getMessage()); 
            	reData.add("上传第" + (++i) + "个文件失败,fileSaveFaile-"+e.getMessage()) ;
            	continue ;
            }
        }

        re.setCode(1);
        re.setData(reData);
        return re;

    }

    public void uploadFileByMappedByteBuffer(MultipartFile file, int chunkNumber, int currentChunkSize,
			int totalChunks, int chunkSize, String type, String carNum, Integer uploads, 
			String uploadFilePathSub, String serverUrl, String uploadsType) throws IOException {
		// TODO Auto-generated method stub

	      String url = null;
	      String fileName = file.getOriginalFilename();
	      String tempDirPath = "D:/home/upload/carImg";

	      //总页数大于1， 证明是已分片
	      if(totalChunks > 1) {
	          File newFile = new File(tempDirPath + fileName);
	          if (newFile.exists())
	        	  newFile.delete(); 
	          String tempFileName = fileName + "_tmp";
	          File tmpDir = new File(tempDirPath);
	          File tmpFile = new File(tempDirPath, tempFileName);
	          if (!tmpDir.exists())
	            tmpDir.mkdirs(); 
	          RandomAccessFile accessTmpFile = new RandomAccessFile(tmpFile, "rw");
	          long offset = chunkSize * (chunkNumber - 1);
	          accessTmpFile.seek(offset);
	          accessTmpFile.write(file.getBytes());
	          accessTmpFile.close();
	          boolean isOk = checkAndSetUploadProgress(file, tempDirPath, chunkNumber, currentChunkSize, totalChunks);
	          System.out.println("上传=" + isOk);
	          if (isOk) {
	        	  boolean flag = renameFile(tmpFile, fileName);
	        	  System.out.println("upload complete !!" + flag + " name=" + fileName);
	          } 
	          if(chunkNumber == totalChunks) {
//	        	  respEntity = readCarInfo(new File(tempDirPath, fileName), carCenter, type, carNum, uploads, tempDirPath, serverUrl, uploadsType);
	        	  //删除临时文件
	              tmpDir.delete();
	              tmpFile.delete();
	          }
	      }else {
	    	  //获取UUID
	          String uuid = UUID.randomUUID().toString().replaceAll("-", "");
	    	  String newFileName = "";
	    	  if(fileName.indexOf(".") != -1) {
	        	  newFileName = fileName.substring(0, fileName.lastIndexOf("."));
	              String extendsFileName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
	              newFileName = newFileName + uuid + extendsFileName;
	          }else {
		        	newFileName += "微信图片_" + fileName + uuid + ".jpg";
		      }
	    	  
	    	  //新增文件file
	          File newFile = new File(tempDirPath, newFileName); 
	          //生成图片文件
//	          FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
//	          respEntity = readCarInfo(newFile, carCenter, type, carNum, uploads, tempDirPath, serverUrl, uploadsType);
	      }
	      
//	      return respEntity;
	}
    private boolean checkAndSetUploadProgress(MultipartFile file, String tempDirPath, int chunkNumber, int currentChunkSize, int totalChunks) {
	    try {
	        String fileName = file.getOriginalFilename();
	        File confFile = new File(tempDirPath, fileName + ".conf");
	        RandomAccessFile accessConfFile = new RandomAccessFile(confFile, "rw");
	        System.out.println("set part " + chunkNumber + " complete");
	        accessConfFile.setLength(totalChunks);
	        System.out.println("总分片数="+ totalChunks);
	        accessConfFile.seek((chunkNumber - 1));
	        System.out.println("ChunkNumber()=" + chunkNumber);
	        accessConfFile.write(127);	
	        byte[] completeList = FileUtils.readFileToByteArray(confFile);
	        System.out.println("数组长="+ completeList.length);
	        System.out.println(Arrays.toString(completeList));
	        byte isComplete = Byte.MAX_VALUE;
	        boolean delete = false;
	        for (int i = 0; i < completeList.length && isComplete == Byte.MAX_VALUE; i++) {
		          isComplete = (byte)(isComplete & completeList[i]);
		          System.out.println("isComplete=" + isComplete);
		          System.out.println("校验  " + i + "完成?" + completeList[i]);
	        } 
	        
	        if (isComplete == Byte.MAX_VALUE) {
	        	delete = confFile.delete();
		    	System.out.println("??" + delete);
		    	confFile.delete();
		        return true;
	        } 
	        return false;
	   } catch (Exception e) {
	        e.printStackTrace();
	        return true;
	   } 
    }
	
	public boolean renameFile(File toBeRenamed, String toFileNewName) {
	    if (!toBeRenamed.exists() || toBeRenamed.isDirectory())
	        return false; 
	    String p = toBeRenamed.getParent();
	    File newFile = new File(p + File.separatorChar + toFileNewName);
	    return toBeRenamed.renameTo(newFile);
    }
	
}

